#!/bin/bash
#
# Program: Google Sitemap Generator
# Purpose: generate google sitemap for small site's htmls
# Author : Sucha <suchaaa@gmail.com>
# Version: 1.00
# Usage  : fill in your htmlpub dir, sitemap file name, your site location,
#          may be you need to edit the changefreq and priority attribute
#
# History: v1.00 - 2008.12.14
#                * run ok under cygwin

# htmlpub and sitemap relative location
htmlpub=$HOME/workport/homepage/publish
sitemap=$htmlpub/sitemap.xml

# sitemap param for find
suffix="*.html"
loc="https://suchang.net/"
lasmodFMT="%FT%T%z"             # strftime format
changefreq="weekly"
priority=0.5

# generate google sitemap
generate_google_sitemap()
{
    htmlpub=$1
    sitemap=$htmlpub/sitemap.xml
    if [ -z "$htmlpub" ]; then
        echo "Usage: generate_google_sitemap PATH_TO_SITEMAP_DIR"
	exit 0
    fi
    echo "generate google sitemap for " $loc " in $htmlpub"

    echo '<?xml version="1.0" encoding="UTF-8"?>' > $sitemap
    echo '<urlset
      xmlns="https://www.sitemaps.org/schemas/sitemap/0.9"
      xmlns:xsi="https://www.w3.org/2001/XMLSchema-instance"
      xsi:schemaLocation="https://www.sitemaps.org/schemas/sitemap/0.9
            https://www.sitemaps.org/schemas/sitemap/0.9/sitemap.xsd">
      <!-- created with shell script in https://suchang.net/cs/ScriptStuff.html -->' >>  $sitemap

    i=1
    for file in $(find $htmlpub -name "$suffix" -type f -print)
    do
        del=$((${#htmlpub} + 2))
        f=$(echo $file | cut -c$del-)

        if [ $(basename $file) == "index.html" ]; then
            pri=1.0
        else
            pri=$priority
        fi

        echo "<url>" >> $sitemap
        echo "<loc>"$loc$f"</loc>" >> $sitemap
        echo "<lastmod>"$(stat -f "%Sm" -t $lasmodFMT $file)"</lastmod>" >> $sitemap
        echo "<changefreq>"$changefreq"</changefreq>" >> $sitemap
        echo "<priority>"$pri"</priority>" >> $sitemap
        echo "</url>" >> $sitemap
        echo ".done $i $file"
        i=$(($i + 1))
    done
    echo '</urlset>' >> $sitemap
}

generate_google_sitemap $1
